// pages/edit-profile/edit-profile.js
import {http} from '../../../utils/requestUtil'
Page({
  data: {
    avatarUrl: '',
    nickName: '',
    phonenumber: '',
    email: ''
  },

  onLoad() {
    // 从全局或缓存加载用户数据
    const userInfo = wx.getStorageSync('userInfo') || {};
    this.setData({
      avatarUrl: userInfo.avatarUrl || '',
      nickName: userInfo.nickName || '',
      phone: userInfo.phonenumber || '',
      email: userInfo.email || ''
    });
  },

  // 更换头像
  changeAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        // 实际开发中这里应上传到服务器
        this.setData({ avatarUrl: tempFilePath });
        
        wx.showToast({
          title: '头像已更新',
          icon: 'success'
        });
      }
    });
  },

  // 处理昵称输入
  onNicknameChange(e) {
    this.setData({ nickName: e.detail.value });
  },

  // 处理电话输入
  onPhoneChange(e) {
    this.setData({ phonenumber: e.detail.value });
  },

  // 处理邮箱输入
  onEmailChange(e) {
    this.setData({ email: e.detail.value });
  },

  // 保存修改
  async saveProfile() {
    const { avatarUrl, nickName, phonenumber, email } = this.data;
    
    // 表单验证
    if (!nickName.trim()) {
      wx.showToast({ title: '昵称不能为空', icon: 'none' });
      return;
    }
    
    if (phonenumber && !/^1[3-9]\d{9}$/.test(phonenumber)) {
      wx.showToast({ title: '手机号格式错误', icon: 'none' });
      return;
    }
    
    if (email && !/\S+@\S+\.\S+/.test(email)) {
      wx.showToast({ title: '邮箱格式错误', icon: 'none' });
      return;
    }
    
    // 保存到缓存（实际应提交到服务器）
    const userInfo = wx.getStorageSync('userInfo') || {};
    // userInfo.avatarUrl = avatarUrl;
    userInfo.nickName = nickName;
    userInfo.phonenumber = phonenumber;
    userInfo.email = email;
    const res = await http.put('/system/user/profile', userInfo)
    console.log(res)
    wx.setStorageSync('userInfo', userInfo);
    
    wx.showToast({
      title: '资料已保存',
      icon: 'success',
      success: () => {
        setTimeout(() => wx.navigateBack(), 1500);
      }
    });
  }
});